import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/buy_sell_bean_entity.dart';
import 'package:wanxiang_app/bean/group_user_entity.dart';
import 'package:wanxiang_app/bean/msg_identity_entity.dart';
import 'package:wanxiang_app/bean/normal_entity.dart';
import 'package:wanxiang_app/bean/qa_list_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/home/qaDetail.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import 'package:wanxiang_app/widgets/account_textField2.dart';
import '../../bean/goods_detail_entity.dart';
import '../../bean/login_entity.dart';
import '../../bean/service_list_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/NoShadowScrollBehavior.dart';
import '../../widgets/chatAppbar.dart';
import '../../widgets/img_dialog.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:nim_core/nim_core.dart';
import 'package:image_picker/image_picker.dart';
import 'package:bot_toast/bot_toast.dart';

import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:http/http.dart' as http;

class ChatController extends GetxController {
   GoodsDetailData? detailData;
  @override
  void onInit() {
    super.onInit();
    // _getService();
    Map map = Get.arguments;
    sessionId = map['sessionId'];
    print('sessionIdsessionId===='+sessionId);
    nickName = map['nickName'];
    print('nickNamenickNamenickName=='+nickName);
    // servicePhoto = map['servicePhoto'];
    teamId= map['account'];
    print('teamIdteamIdteamId=='+teamId);
    myId = UserUtil.getUSER()!.userName.toString();
    if(map['info']!=null){
      detailData = map['info'];
      print('detailData===${detailData!.title}');
    }
    print('myId=====$myId');


    getCreateEmpty();
    _getBuySellList();
    _addListener();
    _queryTeam();
    _getYUnxinTeamMember();
    _topTeam();
    update();
  }

    _getMembers() {
     DioManager.getInstance().getRequest2(ServiceUrl.getImByImg, {},
             (data) async {
           print(data);
           var parsedJson = json.decode(data);

           update();
         }, (error) {
           ToastUtil.show(error);
         });
   }


   getCreateEmpty() async{
    NIMResult<NIMMessage> result1 = await MessageBuilder.createEmptyMessage(
        sessionId: sessionId, sessionType: NIMSessionType.team, timestamp: DateTime.now().millisecondsSinceEpoch);
    _getRecent(result1.data,true);
  }

  @override
  void onClose() {
    super.onClose();
    subsriptions?.cancel();
  }
  String myId = '';
   String teamId = '';
  String nickName = '';
  String sessionId= '';
  int  online = 0;
  String servicePhoto = '';
  List<QaListData> list = [];
  bool emojiShowing = false;
  late LoginData serviceData;
  final ScrollController _scrollController = ScrollController();

  List<NIMMessage> recentList = [];
  _getRecent(NIMMessage? data,bool isFirst) async{
    /// 从本地消息数据库搜索消息历史。
    /// 搜索将返回：时间在 (startTime,endTime) 之间，消息类型为指定类型，且匹配搜索内容或消息发起者列表的一定数量的消息。
    ///
    ///  [sessionType] 会话类型
    ///  [sessionId] 聊天对象ID
    ///  [option] 搜索选项
    ///

    // NIMResult<NIMMessage> result1 = await MessageBuilder.createEmptyMessage(
    //     sessionId: sessionId, sessionType: NIMSessionType.p2p, timestamp: DateTime.now().millisecondsSinceEpoch);

    /// 查询比 anchor时间更早的消息，查询20条，结果按照时间降序排列
    // NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.queryMessageListEx(result1.data!,QueryDirection.QUERY_OLD,30);

    int? newTime = data?.timestamp;
    int oldTime = newTime! - 1000 * 60 * 60*24*30; // 1月前
    List<NIMMessageType> typeList = [];
    typeList.add(NIMMessageType.text);
    typeList.add(NIMMessageType.image);
    typeList.add(NIMMessageType.custom);
    print(oldTime);
    NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.pullMessageHistory(data!,100,true);
    // NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.pullMessageHistoryExType(data!,oldTime,100,QueryDirection.QUERY_OLD,typeList,true);
    if(result.data!.length>0 && result.data?[0].uuid.toString() != data.uuid.toString()){
      recentList = [...?result.data,...recentList];
      // if(isFirst) {
      //   NIMResult<NIMMessage> result1 = await MessageBuilder.createEmptyMessage(
      //       sessionId: '000',
      //       sessionType: NIMSessionType.team,
      //       timestamp: DateTime
      //           .now()
      //           .millisecondsSinceEpoch);
      //   recentList.add(result1.data!);
      // }

      update();
    }

    if(isFirst){
      // Timer(const Duration(milliseconds: 1600),
      //         () => _scrollController.animateTo(_scrollController.position.maxScrollExtent+1550.h, duration: const Duration(milliseconds: 500), curve: Curves.linear));
      Future.delayed(Duration(milliseconds: 500), () {
        _scrollController.jumpTo(0.0);
      });

      _clearMsg();

    }

  }

   String _getDate(timeStamp){
     DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timeStamp);
     DateTime dateTimeNow =DateTime.now();
     if(dateTimeNow.day!=dateTime.day){
       return '${dateTime.month<10?'0${dateTime.month}':dateTime.month }-${dateTime.day<10?'0${dateTime.day}':dateTime.day} ${dateTime.hour<10?'0${dateTime.hour}':dateTime.hour}:${dateTime.minute<10?'0${dateTime.minute}':dateTime.minute}';
       // return '${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}';
     }
     return '${dateTime.hour<10?'0${dateTime.hour}':dateTime.hour}:${dateTime.minute<10?'0${dateTime.minute}':dateTime.minute}';

  }
  bool isInitBuySell = false;
   BuySellBeanData buySellBeanData = BuySellBeanData()  ;
   void _getBuySellList() async{
     Uri urls = Uri.https(Constant.baseUrlIm,ServiceUrl.GetTeams,{'teamsid':teamId});
     var response = await http.get(urls, headers: <String, String>{
       "appKey":Constant.appKey
     },
     );
     var parsedJson = json.decode(response.body);
     print('_getBuySellList_getBuySellList_getBuySellList_getBuySellList==='+teamId);
     print(parsedJson);
     BuySellBeanEntity blackEntity =BuySellBeanEntity.fromJson(jsonDecode(parsedJson));
     buySellBeanData = blackEntity.data;
     // isInitBuySell = true;
    update();
   }

  _clearMsg() async{
    List<NIMSessionInfo> sss= [];
    NIMSessionInfo nimSessionInfo = NIMSessionInfo(sessionId: sessionId, sessionType: NIMSessionType.team);
    sss.add(nimSessionInfo);
    NIMResult<List<NIMSessionInfo>> result = await  NimCore.instance.messageService.clearSessionUnreadCount(sss);
  }

  _sendTextMsg(String text){
    if(text.isEmpty){
      return;
    }
    // 该帐号为示例
    String? account = UserUtil.getUSER()?.mobile;
// 以单聊类型为例
    NIMSessionType sessionType = NIMSessionType.team;
// 创建并且发送一个文本消息

    MessageBuilder.createTextMessage(
        sessionId: sessionId, sessionType: sessionType, text: text
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
        Map honorField = {
          "notification": {  // AndroidNotification
            "bigBody": text,
            "bigTitle": nickName,
            "body": text,
            "title": nickName,
            "buttons": [{
              "actionType": 0,
              "data": "",
              "intent": "",
              "intentType": 0,
              "name": "test"
            }],
            "clickAction": {//	消息点击行为
              "action": "",
              "intent": "intent://com.hihonor.codelabpush",
              "type": 3,//1为打开应用自定义页面，2为点击后打开特定URL，3为点击后打开应用
              "url": ""
            },
            "importance": "NORMAL",
          }
        };
        Map hwField = {
          "click_action": { "type": 1},
          "badge": {
            "add_num": 1,
            "class": "com.example.wangxiang_app.MainActivity",
          }
        };
        result.data!.pushPayload = {"pushTitle":nickName,'honorField':honorField};
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        recentList.insert(0, result.data!);
        _scrollController.jumpTo(0.0);
        return NimCore.instance.messageService
            .sendMessage(message: result.data!);

      } else {
        return result;
      }
    }).then((result) {
      detailData = null;
      print(
          'MessageService##send message: ${result.code} ${result.errorDetails}');
      _clearMsg();
    });
    update();
  }

  _sendCustomerMsg(){
    Map<String,dynamic> map ={
      'img_url':detailData?.imgUrl,
      'price':detailData?.sellPrice,
      'link':"http://103.26.77.113:10000/zmobile/show.aspx?gid="+detailData!.channelId.toString()+'&id='+detailData!.id.toString(),
      'id':detailData?.channelId.toString(),
      'title':detailData?.title,
      'channelName':detailData!.channelName,
      'gId':detailData!.id.toString(),
      'gName':detailData!.goodName
    };

    NIMCustomMessageAttachment attachment =NIMCustomMessageAttachment(data: map);
    detailData = null;
    MessageBuilder.createCustomMessage(  sessionId: sessionId,
      sessionType: NIMSessionType.team,
      attachment: attachment
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        Map honorField = {
          "notification": {  // AndroidNotification
            "bigBody": "[自定义消息]",
            "bigTitle": nickName,
            "body": "[自定义消息]",
            "title": nickName,
            "buttons": [{
              "actionType": 0,
              "data": "",
              "intent": "",
              "intentType": 0,
              "name": "test"
            }],
            "clickAction": {//	消息点击行为
              "action": "",
              "intent": "intent://com.hihonor.codelabpush",
              "type": 3,//1为打开应用自定义页面，2为点击后打开特定URL，3为点击后打开应用
              "url": ""
            },
            "importance": "NORMAL",
          }
        };
        Map hwField = {
          "click_action": { "type": 1},
          "badge": {
            "add_num": 1,
            "class": "com.example.wangxiang_app.MainActivity",
          }
        };
        result.data!.pushPayload = {"pushTitle":nickName,'honorField':honorField};
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        recentList.insert(0, result.data!);
        _scrollController.jumpTo(0.0);
        update();
        return NimCore.instance.messageService
            .sendMessage(message: result.data!);
      } else {
        return result;
      }
    }).then((result) {
      detailData = null;
      _clearMsg();
      print(
          'MessageService##send message: ${result.code} ${result.errorDetails}');
    });
  }

  _sendImageMsg(String path){
    if(path.isEmpty){
      return;
    }
    // 该帐号为示例
    String? account = UserUtil.getUSER()?.mobile;
// 以单聊类型为例
    NIMSessionType sessionType = NIMSessionType.team;
    MessageBuilder.createImageMessage(
      sessionId: sessionId,
      sessionType: NIMSessionType.team,
      filePath: path,
      fileSize: 0,
      displayName: 'image',
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
      //   recentList.add(result.data!);
      // update();
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        // honorField 结构示例
    Map honorField = {
      "notification": {  // AndroidNotification
        "bigBody": "[图片]",
        "bigTitle": nickName,
        "body": "[图片]",
        "title": nickName,
        "buttons": [{
          "actionType": 0,
          "data": "",
          "intent": "",
          "intentType": 0,
          "name": "test"
        }],
        "clickAction": {//	消息点击行为
          "action": "",
          "intent": "intent://com.hihonor.codelabpush",
          "type": 3,//1为打开应用自定义页面，2为点击后打开特定URL，3为点击后打开应用
          "url": ""
        },
        "importance": "NORMAL",
      }
      };
    Map hwField = {
      "click_action": { "type": 1},
      "badge": {
        "add_num": 1,
        "class": "com.example.wangxiang_app.MainActivity",
      }
    };
        result.data!.pushPayload = {"pushTitle":nickName,'honorField':honorField,};
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        BotToast.showLoading();
        Future<NIMResult<NIMMessage>> ff= NimCore.instance.messageService
            .sendMessage(message: result.data!);
        ff.then((value) => {
        BotToast.closeAllLoading(),
        recentList.insert(0, value.data!),
            _scrollController.jumpTo(0.0),
          update()
        });
        _clearMsg();
        return ff;
      } else {
        return result;
      }
    }).then((result) {
      print(
          'MessageService##send message: ${result.code} ${result.errorDetails}');
    });

  }
   StreamSubscription? subsriptions ;
  _addListener(){
    subsriptions = NimCore.instance.messageService.onMessage.listen((messages) {
      List<NIMMessage> aa = [];
      for(var item in messages){
        if(item.sessionId == sessionId){
          aa.add(item);
        }
      }
      recentList.insertAll(0,aa);
            _clearMsg();
            // _scrollController.jumpTo(0.0);
            update();


    });
  }
  _emojText(String text){
    text.runes.forEach((rune) {
      String str = new String.fromCharCode(rune);
    });
  }
  bool isFirstRefresh = true;
   EasyRefreshController easyRefreshController = EasyRefreshController(
     controlFinishRefresh: true,
     controlFinishLoad: true,
   );

  _dealPhone(String text){
    print('bbbbbb='+text);
    if(text.length==11){
      return text.substring(0,3)+'****'+text.substring(7,11);
    }
    return text;
  }
   List<NIMTeamMember> teamMebers = [];
  _getYUnxinTeamMember() async {

    NIMResult<List<NIMTeamMember>> aa= await NimCore.instance.teamService.queryMemberList(teamId);
    if(aa.isSuccess){
      teamMebers = aa.data!;
    }
    getUserList();
  }

   _queryTeam() async {

     NIMResult<NIMTeam> aa= await NimCore.instance.teamService.queryTeam(teamId);
     if(aa.isSuccess){
       if( aa.data!.messageNotifyType == NIMTeamMessageNotifyTypeEnum.mute){
         isMute.value = true;
       }else{
         isMute.value = false;
       }
       print('isMute=='+isMute.value.toString());
       update();
     }

   }

   List groupMember = [];
   void getUserList() async{
     List cc = [];
     for(var item in teamMebers){
       Map dd = {"account":item.account};
       cc.add(dd);
     }
     print('~~~~~~~~~~~~~~~~');
     print(json.encode({'members':cc}));
     Uri urls = Uri.http(Constant.baseUrlIm,'api/IMCCWebApi/GetUserList',{});
     var response = await http.post(urls, headers: <String, String>{
       'Content-Type': 'application/json',
       "Accept": "application/json",
       "appKey": Constant.appKey,
     },
         body: json.encode({'members':cc})
     );

     var parsedJson = json.decode(response.body);
     print('parsedJsonparsedJsonparsedJson');
     print(parsedJson);
     GroupUserEntity bannerEntity =  GroupUserEntity.fromJson(jsonDecode(parsedJson));
     List<GroupUserDataUserList>  userList = bannerEntity.data.userList;
     imList = bannerEntity.data.imList;
     for(var item in imList){
       Map map = {'nickname':item.nickname,'photo':  Constant.IMG_NET_BASE+item.photo,'id':item.account,'type':'gov'};
       groupMember.add(map);
     }

     for(var item in userList){
       Map map = {'nickname':item.nickName,'photo': Constant.IMG_NET_BASE+item.userPhoto,'id':item.userName,'type':'user'};
       groupMember.add(map);
     }

     getTeamById();
     update();
   }
   late MsgIdentityData msgIdentityData ;
   List<GroupUserDataImList> imList=[];
   void getTeamById() async{
     List cc = [];
     for(var item in teamMebers){
       Map dd = {"account":item.account};
       cc.add(dd);
     }
     print('~~~~~~~~~~~~~~~~');
     print(json.encode({'members':cc}));
     Uri urls = Uri.http(Constant.baseUrlIm,'api/IMCCWebApi/GetTeamsListByAccount',{'account':imList[0].account.toString()});
     var response = await http.get(urls, headers: <String, String>{
       'Content-Type': 'application/json',
       "Accept": "application/json",
       "appKey": Constant.appKey,
     },
     );

     var parsedJson = json.decode(response.body);
     print('getTeamByIdgetTeamByIdgetTeamByIdgetTeamById');
     print(parsedJson);
     MsgIdentityEntity bannerEntity =  MsgIdentityEntity.fromJson(jsonDecode(parsedJson));
     for(var item in bannerEntity.data){
       if(item.teamId==teamId){
         msgIdentityData = item;
         break;

       }
     }
     print('===============================');
     print(msgIdentityData.id.toString());
     print(msgIdentityData.buyerAccount);
     print(msgIdentityData.sellerAccount);
     print('===============================');
     isInitBuySell = true;

     update();
   }

   var isMute = false.obs;
   var isTop = false.obs;

   _muteTeam() async{
     var result = await NimCore.instance.teamService.muteTeam(
         teamId,
         isMute.value?NIMTeamMessageNotifyTypeEnum.all:NIMTeamMessageNotifyTypeEnum.mute);
     if(result.isSuccess){
       isMute.value = !isMute.value;
       update();
     }

   }


   _topTeam() async{
    var aa= await NimCore.instance.messageService.queryStickTopSession();
    if(aa.isSuccess){
     List<NIMStickTopSessionInfo> bb = aa.data!;
     for(var item in bb){
       if(item.sessionId == sessionId){
         isTop.value = true;
         break;
       }
     }
    }

    print('isTop=='+isTop.value.toString());

    update();

   }
   _top() async{
     var aa ;
     if(isTop.value){
        aa = await  NimCore.instance.messageService.removeStickTopSession(sessionId, NIMSessionType.team, "");
     }else{
        aa = await  NimCore.instance.messageService.addStickTopSession(sessionId, NIMSessionType.team, "");
     }
     isTop.value =   !isTop.value ;
     update();
   }

   _clearAll(){
     NimCore.instance.messageService.clearChattingHistory(teamId, NIMSessionType.team, false);
     NimCore.instance.messageService.clearMsgDatabase(true);
   }

  _getAvater(NIMMessage msg){

    for(var item in groupMember){
      if(item['id'] == msg.fromAccount.toString()){
        return item;
      }
    }
  }

   _getNickName(String text){
     if(text.length>12){
       return text.substring(0,12)+'...';
     }
     return text;
   }

   _msgFilter(String msg){
     if(msg.contains("@")){
       for(int i=0; i<msg.length; i++) {
         var char = msg[i];
         if(char=='@'){
           int index  = i;
           String aa = msg.substring(index,msg.length);
           if(aa.length>=11){
             String pre = msg.substring(0,index);
             String bb = msg.substring(index+1,index+12);

             if(bb.contains(new RegExp(r'^[0-9]+$'))){
               bb= _dealPhone(bb);
               String after = msg.substring(index+12,msg.length);
               return pre+'@'+bb+after;
             }
           }
         }
       }

     }
     return msg;
   }

   _getOwer(id){
     print('_getOwer==='+id.toString());
     for(var item in groupMember){
       if(id == item['id'] ){
        return item['type'];
       }
     }
   }
}

class GroupPage extends GetView<ChatController> {
  late ChatController controller;

  late BuildContext context;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<ChatController>(() => ChatController());

    controller = Get.find();
    context = context1;
    return GetBuilder<ChatController>(
      builder: (_) {
        return Scaffold(
            appBar: ChatAppBar(
              context: context,
              online: 3,
              title: controller._getNickName(controller.nickName) ,
              callBack: ((){
                _showSet();
              }),
              hasLeading: true,
            ),
            backgroundColor: const Color(0xfff7f8fc),
            body:  _content());
      },
    );
  }



  Widget _content() {
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).unfocus();
      },
      child: Container(
        height: Get.height,
        child: Stack(children: [
          // ScrollConfiguration(
          //   behavior: NoShadowScrollBehavior(),
          //   child: SingleChildScrollView(
          //     physics: ClampingScrollPhysics(),
          //       controller: controller._scrollController,
          //       child:  Container(
          //           width: Get.width,
          //           margin: EdgeInsets.only(bottom: 120.h),
          //           child: Column(
          //             children:_all(),
          //           )
          //       )
          //   ),
          // )
          Container(
            alignment: Alignment.topCenter,
              height: Get.height,
              width: Get.width,
              margin: EdgeInsets.only(bottom: 80.h),
            child:  EasyRefresh(
              header: ClassicHeader(
                dragText: 'Pull to refresh'.tr,
                armedText: 'Release ready'.tr,
                readyText: 'Refreshing...'.tr,
                processingText: 'Refreshing...'.tr,
                processedText: 'Succeeded'.tr,
                noMoreText: 'No more'.tr,
                failedText: 'Failed'.tr,
                messageText: 'Last updated at %T'.tr,
              ),
              footer: NotLoadFooter(),
              controller: controller.easyRefreshController,
              onRefresh: () async {
                if(controller.isFirstRefresh){
                  print('onRefreshonRefreshonRefresh111');
                  controller.isFirstRefresh = false;
                  controller.easyRefreshController.finishRefresh(
                      IndicatorResult.success );
                }else{
                  print('onRefreshonRefreshonRefresh222');
                  controller.easyRefreshController.finishRefresh(
                      IndicatorResult.success );
                }
              },
              onLoad: () async {
                if(controller.isFirstRefresh){
                  print('onLoadonLoadonLoad111');
                  controller.isFirstRefresh = false;
                  controller.easyRefreshController.finishLoad( IndicatorResult.success
                      );
                }else{
                  print('onLoadonLoadonLoad222');
                  controller.easyRefreshController.finishLoad( IndicatorResult.success );
                  controller._getRecent(controller.recentList[0],false);
                }



              },
              child: ListView.builder(
                reverse: true,
                shrinkWrap:true,
                controller: controller._scrollController,
                itemBuilder: (context, index) {
                  if(controller.recentList[index].sessionId=='000'){
                    return _goodsInfo();
                  }

                  else if(controller.recentList[index].messageType==NIMMessageType.notification){
                  return _notice(controller.recentList[index]);
                  }
                  else if(controller.recentList[index].fromAccount==controller.myId){
                    return _right(controller.recentList[index]);
                  }else{
                    return _left(controller.recentList[index]);
                  }
                }, itemCount: controller.recentList.length,
              ),
            )
          )
          ,
          Positioned(bottom: 0, child: _bottom())
        ])
      )
    ) ;
  }

  List<Widget> _all(){
    List<Widget> aa = [];
    for(var item in controller.recentList){
      if(item.fromAccount==controller.myId){
        aa.add(_right(item));
      }else{
        aa.add(_left(item));
      }
    }
    if(controller.detailData!=null){
      aa.add(_goodsInfo());
    }
    return aa;
  }

  Widget _left(NIMMessage msg) {
    var map =  controller._getAvater(msg);
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ClipOval(

                 child: Image.network(

                   (map==null||map['photo']==null || map['photo']=='')?'http://p.taohaoge.com/images/uploadFailedNewImg.png':map['photo'],
      width: 50.w,
      height: 50.w,
                   fit: BoxFit.cover,
    ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: 5.w,
                      ),
                      Text(
                        (map==null||map['nickname']==null || map['nickname']=='')?'':
                        Common.simpleNick(map['nickname']) ,
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontWeight: FontWeight.bold,
                            fontSize: 14.sp),
                      ),
                      SizedBox(
                        width: 2.w,
                      ),
                      _buyer(msg.fromAccount),
                      controller._getOwer(msg.fromAccount.toString())=='gov'?
                      Image.asset(
                        Constant.IMG_BASE + 'gov.png',
                        width: 26.w,
                        height: 13.h,
                      ):Container(),
                      Container(
                          margin: EdgeInsets.only(left: 5.w, ),
                          child: Text(controller._getDate(msg.timestamp),style:TextStyle(
                              fontSize: 12.sp
                          ) )),
                    ],
                  ),

                  Container(
                    padding: EdgeInsets.all(10.w),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(5.r)),
                    child: ConstrainedBox(
                        constraints: BoxConstraints(
                          maxWidth: 200.w,
                        ),
                        child:_msg(msg,true)),
                  )


                ],
              ),

            ],
          ),

        ],
      ),
    );
  }

  Widget _gallery(url,context1){
    return  Container(
      height: Get.height - 30.h,
      child: Material(
          type: MaterialType.transparency,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                onTap: (){
                  Navigator.of(context1).pop();
                },
                child:  Container(
                    height:  Get.height - 30.h,
                    width: Get.width,
                    child: PhotoViewGallery.builder(
                      scrollPhysics: const BouncingScrollPhysics(),
                      builder: (BuildContext context, int index) {
                        return PhotoViewGalleryPageOptions(
                          imageProvider: NetworkImage(Common.realPicPath(url) ),
                          initialScale: PhotoViewComputedScale.contained * 0.8,
                          heroAttributes: PhotoViewHeroAttributes(tag: 'imgs'),
                        );
                      },
                      itemCount: 1,
                      backgroundDecoration:  BoxDecoration(color: Colors.black12),
                    )
                )
              )
             ,

            ],
          )
      )  ,
    ) ;
  }

  Widget _emojH5(String text,bool isLeft){
    String aa = text.substring(1,text.length-1);
    if(aa.startsWith('ajmd')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/ajmd/'+aa+'.png',
      );
    }
    else if(aa.startsWith('arclist')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/arclist/'+aa+'.png',
      );
    } else if(aa.startsWith('lt')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/lt/'+aa+'.png',
      );
    }else if(aa.startsWith('xxy')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/xxy/'+aa+'.png',
      );
    }
    else{

      String cc = Common.emoji[text]['file'];
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/emoji/'+cc,
      );
    }

  }

  Widget _msg(NIMMessage msg,bool isLeft){

    if(msg.messageType == NIMMessageType.text){
      if(msg.content!.startsWith('[')){
        return _emojH5( msg.content!,isLeft);
      }else{
        return SelectableText(
          controller._msgFilter( msg.content!),
          style: TextStyle(color:isLeft?Colors.black:Colors.white),
        );
      }

    }
    if(msg.messageType == NIMMessageType.image){
      if(msg.messageAttachment==null || (msg.messageAttachment?.toMap())?['thumbUrl']==null){
        return Container();
      }
     return
       InkWell(
         onTap: (){
           // showDialog(context: context, builder: (BuildContext context1) {
           //   return MyPhotoDialog(url: (msg.messageAttachment?.toMap())?['url'],
           //   );
           // });

           showDialog(
               context: context,

               builder: (context1) {
                 return  _gallery(msg.messageAttachment?.toMap()?['url'],context1);
               });

         },
         child: Image.network((msg.messageAttachment?.toMap())?['thumbUrl'],fit: BoxFit.contain,)
       );

    }
    if(msg.messageType == NIMMessageType.custom){
      if(msg.messageAttachment==null){
        return Container();
      }
      NIMCustomMessageAttachment attachment = msg.messageAttachment as NIMCustomMessageAttachment;
      Map? map = {};
      if(attachment.data?['data']  == null){
        map = attachment.data;
      }else{
        map =attachment.data?['data'] ;
      }
      return InkWell(
        onTap: (){
          // 'id':detailData?.id.toString(),
          // 'title':detailData?.title,
          // 'channelName':detailData!.channelName,
          // 'gName':detailData!.goodName

          Get.to(()=>DetailPage(),arguments: {
            "title":map?['gName'],
            "record_id":'',
            "channel_name":map?['channelName'],
            "goods_id":map?['gId'],
          },preventDuplicates:false);
        },
        child: Container(
          width: 200.w,
          child: Row(
            children: [
              Image.network(Common.realPicPath(map?['img_url']),width: 40.w,height: 40.h,fit: BoxFit.cover,),
              Container(
                  margin: EdgeInsets.only(left: 5.w),
                  width: 150.w,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(map?['title'],style: const TextStyle(
                        overflow: TextOverflow.ellipsis,
                      ),maxLines: 2,),
                      // Text('¥ '+map?['price'],style: TextStyle(
                      //     color: Colors.white
                      // ),),
                    ],
                  )
              )

            ],
          ),
        )
      ) ;
    }
    return Container();
  }


  Widget _right(NIMMessage msg) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Row(
                    children: [
                      Text(UserUtil.getUSER()!.nickname,style: const TextStyle(
                          color: Color(0xFF999999)
                      ),),
                      SizedBox(width: 3.w,),
                      _buyer(msg.fromAccount),
                      SizedBox(width: 3.w,),
                      Text(controller._getDate(msg.timestamp),style: const TextStyle(
                          color: Color(0xFF999999)
                      ),),

                    ],
                  ),
                  Container(
                      margin: EdgeInsets.only(top: 5.h),
                      padding: EdgeInsets.all(10.w),
                      decoration: BoxDecoration(
                          color: msg.messageType == NIMMessageType.custom?Colors.white: Color(0xFF007BE5),
                          borderRadius: BorderRadius.circular(5.r)),
                      child: ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: 250.w,
                          ),
                          child:   _msg(msg,false))
                  )
                ],
              ),
              SizedBox(width: 3.w,),
              Column(
                children: [

                  Container(
                      width: 50.w,
                      height: 50.w,
                      child:    ClipOval(
                          child:  Image.network(
                            UserUtil.getUSER()!.userPhoto,
                            width: 50.w,
                            height: 50.w,
                            fit: BoxFit.cover,
                          )
                      )
                  ),

                ],
              )


              ,
            ],
          ),

        ],
      ),
    );
  }

  Widget _notice(NIMMessage msg){
    if(msg.messageAttachment==null || msg.messageAttachment!.toMap()?['targets']==null){
      return Container();
    }
    List<String> aa=msg.messageAttachment!.toMap()?['targets'];
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(controller._dealPhone(aa[0]),style: TextStyle(
          color: Color(0xFF999999)
        ),),
        SizedBox(width: 5.w,),
        Text('加入群聊',style: TextStyle(
          color: Color(0xFF007BE5)
        ),),
      ],
    );
  }
  
  Widget _goodsInfo(){
    return controller.detailData==null?Container():
    Container(
      padding: EdgeInsets.all(10.w),
      margin: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Color(0xffdddee1),width: 1.w),
      ),
      child: Column(
        children: [
          Container(
            width: Get.width - 50.w,
            child:  Row(
              children: [
                Image.network(Common.realPicPath(controller.detailData!.imgUrl) ,width: 60.w,height: 60.h,fit: BoxFit.cover,),
                SizedBox(width: 10.w,),
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                        width: Get.width - 50.w - 100.w,
                      child: Text(controller.detailData!.title,
                        style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,)
                    )
                    ,
                    Row(
                      children: [
                        Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                        Text(controller.detailData!.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 16.sp),),
                      ],
                    )
                  ],
                )
              ],
            )
          ),
           Container(height: 0.5.h,color: Colors.grey,margin: EdgeInsets.only(top: 10.h,bottom: 10.h),),
           InkWell(
             onTap: (){
              controller._sendCustomerMsg();
             },
             child:  Text('发送链接',style: TextStyle(
                 color: Color(0xFF007BE5),
                 fontSize: 16.sp
             ),)
           )

        ],

      ),
    );
  }

Widget _buyer(account){
    print('accountaccountaccount===='+account.toString());
    if(!controller.isInitBuySell){
      return Container();
    }
    if(account==controller.msgIdentityData.sellerAccount){
      return Container(
        margin: EdgeInsets.only(left: 2.w,right: 2.w),
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 5.w,right: 5.w,top: 2.h,bottom: 2.h),
        decoration: BoxDecoration(
            color: Color(0xFF007BE5)
        ),
        child: Text('卖',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
      );
    }
    if(account==controller.msgIdentityData.buyerAccount){
      return Container(
        margin: EdgeInsets.only(left: 2.w,right: 2.w),
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 5.w,right: 5.w,top: 2.h,bottom: 2.h),
        decoration: BoxDecoration(
            color: Color(0xFFFF0000)
        ),
        child: Text('买',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
      );
    }
    return Container();

}


  Widget _buildInputTextComposer() {
    return Container(
        width: Get.width - 130.w-20.w - 12.w,
        constraints: BoxConstraints(maxHeight: 80.h,),

        child: SingleChildScrollView(
          child: TextField(
            style: const TextStyle(fontSize: 16),
            controller: _textController,
            maxLines: null,
            onTap: (){
              controller.emojiShowing = false;
              controller.update();
            },
          )
        ) );
  }

  TextEditingController _textController =
      TextEditingController(); // 用来监听TextField的输入内容

  _onBackspacePressed() {
    _textController
      ..text = _textController.text.characters.toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _textController.text.length));
  }

  Widget _bottom() {
    return Container(
      width: Get.width,
      height: controller.emojiShowing ? 310.h : 80.h,
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              IconButton(
                onPressed: () {
                  FocusScope.of(context).unfocus();
                  controller.emojiShowing = !controller.emojiShowing;
                  controller.update();
                },
                icon: const Icon(
                  Icons.mood,
                  size: 28,
                ),
              ),
              _buildInputTextComposer(),
              IconButton(
                onPressed: () async{
                  FocusScope.of(context).unfocus();
                  final ImagePicker picker = ImagePicker();
                  final XFile? image = await picker.pickImage(source: ImageSource.gallery);
                  controller._sendImageMsg(image!.path);
                },
                icon: const Icon(
                  Icons.photo,
                  size: 28,
                ),
              ),
              InkWell(
                  onTap: () {
                   controller._sendTextMsg(_textController.text);
                   _textController.text= '';
                    FocusScope.of(context).unfocus();
                   controller.emojiShowing=false;
                   controller.update();
                  },
                  child: Container(
                    margin: EdgeInsets.only(right: 5.w),
                    decoration: const BoxDecoration(
                      color: Color(0xFF007BE5),
                    ),
                    alignment: Alignment.center,
                    width: 60.w,
                    height: 30.h,
                    child: const Text(
                      '发送',
                      style: TextStyle(color: Colors.white),
                    ),
                  ))
            ],
          ),
           controller.emojiShowing? SizedBox(
                  height: 250.h,
                  child: EmojiPicker(
                    textEditingController: _textController,
                    onBackspacePressed: _onBackspacePressed,
                    config: Config(
                      columns: 7,
                      emojiSizeMax: 32 *
                          (foundation.defaultTargetPlatform ==
                                  TargetPlatform.iOS
                              ? 1.30
                              : 1.0),
                      verticalSpacing: 0,
                      horizontalSpacing: 0,
                      gridPadding: EdgeInsets.zero,
                      initCategory: Category.RECENT,
                      bgColor: const Color(0xFFF2F2F2),
                      indicatorColor: Colors.blue,
                      iconColor: Colors.grey,
                      iconColorSelected: Colors.blue,
                      backspaceColor: Colors.blue,
                      skinToneDialogBgColor: Colors.white,
                      skinToneIndicatorColor: Colors.grey,
                      enableSkinTones: true,
                      recentTabBehavior: RecentTabBehavior.RECENT,
                      recentsLimit: 28,
                      replaceEmojiOnLimitExceed: false,
                      noRecents: const Text(
                        'No Recents',
                        style: TextStyle(fontSize: 20, color: Colors.black26),
                        textAlign: TextAlign.center,
                      ),
                      loadingIndicator: const SizedBox.shrink(),
                      tabIndicatorAnimDuration: kTabScrollDuration,
                      categoryIcons: const CategoryIcons(),
                      buttonMode: ButtonMode.MATERIAL,
                      checkPlatformCompatibility: true,
                    ),
                  )):Container(),
        ],
      ),
    );
  }

  List<Widget> _teamList(){
    List<Widget> aa = [];
    for(var item in controller.groupMember){
      aa.add(_teamMember(item));
    }
    return aa;
  }

  Widget _teamMember(item){
    return Container(
      margin: EdgeInsets.only(left: 10.w),
      width: 60.w,
      child: Column(
        children: [
      ClipOval(
        child:  Image.network(item['photo'],width: 60.w,height: 60.w,fit: BoxFit.cover),
      ),
          Text(item['nickname'], overflow: TextOverflow.ellipsis,)
        ],
      )
    ) ;
  }

  Future<Future<int?>> _showSet() async {
    return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return  AnimatedPadding(
            padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
            duration: const Duration(milliseconds: 100),
            child: Container(
              padding: EdgeInsets.all(10.w),
              clipBehavior: Clip.antiAlias,
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              height: MediaQuery.of(context).size.height / 1.5,
              child: Column(children: [
                SizedBox(
                  height: 50,
                  child: Stack(
                    textDirection: TextDirection.rtl,
                    children: [
                      const Center(
                        child: Text(
                          '设置',
                          style: TextStyle(
                            fontSize: 15,
                            color: Color(0xFF333333),
                          ),
                        ),
                      ),
                      IconButton(
                          icon: Icon(Icons.close),
                          onPressed: () {
                            Navigator.of(context).pop();
                          }),
                    ],
                  ),
                ),

                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        SizedBox(
                          height: 12.h,
                        ),
                        SingleChildScrollView(
                          child: Row(
                            children: _teamList(),
                          )
                        ),
                        Container(height: 1.h,width: Get.width,color: Color(0xFFF7F7F6),margin: EdgeInsets.only(top: 10.h,bottom: 10.h),),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('群组名称'),
                            Text(controller.nickName,style: TextStyle(fontSize: 13.sp),),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('消息免打扰'),
                            Obx(() =>
                            Switch(
                                inactiveThumbColor: Colors.white,
                                inactiveTrackColor: Color(0xffdcdcdc),
                                activeColor: Colors.white,
                                activeTrackColor: Color(0xff007be5),
                                value: controller.isMute.value,
                                onChanged: (value) {
                                  controller._muteTeam();

                                }))
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('置顶聊天'),
                            Obx(() =>
                                Switch(
                                    inactiveThumbColor: Colors.white,
                                    inactiveTrackColor: Color(0xffdcdcdc),
                                    activeColor: Colors.white,
                                    activeTrackColor: Color(0xff007be5),
                                    value: controller.isTop.value,
                                    onChanged: (value) {
                                      controller._top();
                                    }))
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('聊天记录'),
                            IconButton(
                              onPressed: () async{
                                FocusScope.of(context).unfocus();
                                final ImagePicker picker = ImagePicker();
                                final XFile? image = await picker.pickImage(source: ImageSource.gallery);
                                controller._sendImageMsg(image!.path);
                              },
                              icon: const Icon(
                                Icons.arrow_forward_ios,
                                color: Color(0xffdcdcdc),
                                size: 24,
                              ),
                            )
                          ],
                        ),
                        InkWell(
                          onTap: (){
                            controller._clearAll();
                          },
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('清空聊天记录'),
                              IconButton(
                                onPressed: () async{
                                },
                                icon: const Icon(
                                  Icons.arrow_forward_ios,
                                  color: Color(0xffdcdcdc),
                                  size: 24,
                                ),
                              )
                            ],
                          )
                        )
                       ,
                      ],
                    ),
                  ),
                ),
              ]),
            ));
      },
    );
  }

}
